package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Service
public class ReportServiceImpl implements ReportService {
    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WorkSpaceService workSpaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.获取营业额统计表
        ArrayList<LocalDate> timeList = new ArrayList<>();
        timeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            timeList.add(begin);
        }

        // 2.遍历时间
        ArrayList<BigDecimal> turnoverList = new ArrayList<>();

        for (LocalDate localDate : timeList) {
            BigDecimal bigDecimal = orderMapper.sumByCondition(Orders.COMPLETED, localDate);
            turnoverList.add(bigDecimal);
        }

        // 封装结果
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(timeList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO turnoverUserStatistics(LocalDate begin, LocalDate end) {
        LocalDate beforeDate = begin.minusDays(1);
        //1.获取营业额统计表
        ArrayList<LocalDate> timeList = new ArrayList<>();
        timeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            timeList.add(begin);
        }
        // 2.遍历时间 获取新用户
        ArrayList<Integer> newUserList = new ArrayList<>();
        ArrayList<Integer> allUserList = new ArrayList<>();

        // select count(*) from user where create_time<=日期
        Map<Object, Object> param = new HashMap<>();
        param.put("allUserDate", beforeDate);
        Integer allUserBeforeCount = userMapper.countByMap(param);

        for (LocalDate localDate : timeList) {
            param.put("allUserDate", null);
            param.put("newUserDate", localDate);

            Integer newUserCount = userMapper.countByMap(param);
            newUserList.add(newUserCount);
            allUserBeforeCount += newUserCount;
            allUserList.add(allUserBeforeCount);
        }
        return UserReportVO.builder()
                .newUserList(StringUtils.join(newUserList, ","))
                .dateList(StringUtils.join(timeList, ","))
                .totalUserList(StringUtils.join(allUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.获取营业时间统计表
        ArrayList<LocalDate> timeList = new ArrayList<>();
        timeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            timeList.add(begin);
        }
        // 申明时间区间内的订单总量/有效订单总量/订单完成率变量
        double orderCompletionRate = 0.0;
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        // 2.环遍历时间列表，统计每一天的订单总量/有效订单量
        ArrayList<Integer> totalOrderCountList = new ArrayList<>();//一天的订单总量列表
        ArrayList<Integer> validOrderCountList = new ArrayList<>();// 每一天的有效订单量列表

        for (LocalDate date : timeList) {
            HashMap<Object, Object> param = new HashMap<>();
            param.put("date", date);
            Integer totalOrder = orderMapper.countByMap(param);

            param.put("status", Orders.COMPLETED);
            Integer validOrder = orderMapper.countByMap(param);

            totalOrderCountList.add(totalOrder);
            validOrderCountList.add(validOrder);

            //累加每一天的订单量
            totalOrderCount += totalOrder;
            validOrderCount += validOrder;
        }
        orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(timeList, ","))//时间列表
                .orderCountList(StringUtils.join(totalOrderCountList, ","))//订单总量列表
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))


                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO topTen(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.topTen(begin, end);

        // 2．处理查询结果
        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<Integer> numList = new ArrayList<>();

        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            nameList.add(goodsSalesDTO.getName());
            numList.add(goodsSalesDTO.getNumber());
        }

        //3.封装V0
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numList, ","))
                .build();

    }

    /**
     * 导出Excel报表
     */
    @Override
    public void exportExcel(HttpServletResponse response) throws IOException, ExecutionException, InterruptedException {
        //1。创建excel对象（在内存中）
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream("kk.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(stream);
        // 2.创建sheet页对象
        XSSFSheet sheet = excel.getSheet("Sheet1");
        //3.创建row行对象
        sheet.getRow(3).getCell(2).setCellValue(666);

        LocalDate now = LocalDate.now();// 2-27
        LocalDate date = now.minusDays(30);//1-27

        Double turnover = 0.0;// 月营业额
        Integer validorderCount = 0;//月有效订单
        Integer newUsers = 0;//月新增用户数

        for (int i = 0; i < 30; i++) {
            BusinessDataVO businessData = workSpaceService.getBusinessData(date);
            sheet.getRow(7 + i).getCell(1).
                    setCellValue(date.toString());
            sheet.getRow(7 + i).getCell(2).setCellValue(businessData.getTurnover().toString());
            sheet.getRow(7 + i).getCell(3).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(7 + i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(7 + i).getCell(5).setCellValue(businessData.getUnitPrice());
            sheet.getRow(7 + i).getCell(6).setCellValue(businessData.getNewUsers());

            date = date.plusDays(1);

            turnover += businessData.getTurnover().doubleValue(); //累加月营业额
            validorderCount += businessData.getValidOrderCount();//累加月有效订单
            newUsers += businessData.getNewUsers();//加月新增用户
        }
        // 调用持久层
        HashMap<Object, Object> param = new HashMap<>();
        param.put("begin", LocalDate.now().minusDays(30));
        param.put("end", LocalDate.now().minusDays(1));
        Integer totalOrderCount = orderMapper.countByMap(param);
        // 写入数据
        sheet.getRow(3).getCell(2).setCellValue(turnover);//一个月的营业额
        sheet.getRow(3).getCell(4).setCellValue(validorderCount.doubleValue() / totalOrderCount);//个月的新增用户数据
        sheet.getRow(3).getCell(6).setCellValue(newUsers);//个月的新增用户数据

        sheet.getRow(4).getCell(2).setCellValue(validorderCount);//一个月的营业额
        sheet.getRow(4).getCell(4).setCellValue(turnover /validorderCount);//一个月的营业额
        // 写入
        excel.write(response.getOutputStream());

        excel.close();
        System.out.println("操作完毕");
    }
}
